﻿Imports System.IO
Imports System.Xml.Serialization
Imports HybrisItemViewer.HybrisItems.ViewerSave
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Runtime.Serialization.Formatters.Binary

Public Class Main

    Dim CParser As HybrisItems.ConfigParser

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles BtnImportBrowse.Click

        OpenFileDialog1.InitialDirectory = TxtImportBrowse.Text
        Dim openFileResults = OpenFileDialog1.ShowDialog()

    End Sub

    Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk

        Dim strm As System.IO.Stream
        strm = OpenFileDialog1.OpenFile()
        TxtImportBrowse.Text = OpenFileDialog1.FileName.ToString()

    End Sub

    Private Sub BtnImport_Click(sender As System.Object, e As System.EventArgs) Handles BtnImport.Click

        CParser = New HybrisItems.ConfigParser

        Select Case CParser.LoadXml(TxtImportBrowse.Text)

            Case HybrisItems.ConfigParser.ValidateResults.Failed
                MsgBox("Failed to parse items.config.")

            Case HybrisItems.ConfigParser.ValidateResults.Success
                MsgBox("Debug: Success")

                CParser.ExtractEntireModel()

        End Select

    End Sub

    Private Sub BtnSave_Click(sender As System.Object, e As System.EventArgs) Handles BtnSave.Click

        Dim SaveDir As String = SaveClass.SavePath & TxtSaveName.Text
        Dim SaveFileName As String = SaveDir & "\save.hbs"

        Dim SaveModel As New SaveClass
        SaveModel.Model = CParser.Model
        'SaveModel.XMLDocs = CParser.XMLDocNames_HybrisModelBin

        If File.Exists(SaveFileName) Then

            Dim reply As DialogResult = MessageBox.Show("Overwrite existing save?", "Save Exists", _
              MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)

            If Not reply = DialogResult.Yes Then
                Exit Sub
            Else
                File.Delete(SaveFileName)
            End If

        Else

            Directory.CreateDirectory(SaveDir)

        End If

        'Serialize object to a text file.
        Dim fs As FileStream
        Dim formatter As New BinaryFormatter
        Try

            fs = New FileStream(SaveFileName, FileMode.Create)
            formatter.Serialize(fs, SaveModel)

        Catch ex As Exception
            Throw ex
        Finally

            If Not fs Is Nothing Then
                fs.Close()
            End If

        End Try

    End Sub

End Class